/**
 * axios封装
 * 请求拦截、响应拦截、错误统一处理
 */
 const CryptoJS = require('./we_sha256').SHA256;
 import axios from 'axios';
 import router from '../router';
 import store from '../store/index';
 import { ElNotification } from "element-plus";
 /** 
 * 提示函数 
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
    ElNotification({
        message: msg
      });    
}
/** 
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
    router.replace({
        path: '/login',        
        query: {
            redirect: router.currentRoute.fullPath
        }
    });
}

axios.defaults.timeout = 5000; //响应时间
// 允许携带cookie
axios.interceptors.request.use(
    // element ui Loading方法
    function (config) {
        if (config.method == 'post') {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        }
        let token = JSON.parse(localStorage.getItem("token"));
        let t3=getTimeStr();    //时间戳
        let signature = CryptoJS.SHA256(token + t3).toString(CryptoJS.enc.Hex).toUpperCase();
        localStorage.setItem("signature",signature)
        if (token) {
            config.headers.common['SIGN'] = signature;
            config.headers.common['WEBMARK'] = token;
            // config.headers.common['Cookie']='53revisit=1616037883125;tanxiaji=qcefr69u8eh99zpsgdfmxo1uknt3zp4m'
        }
        return config;
    },
    function (error) {
        return Promise.reject(error)
    }
)
//全局拦截
axios.interceptors.response.use(response => {
    if (response.errno == 201103 || response.errno == 201104) {
        ElNotification.alert('登录失效', '提示', {
            confirmButtonText: '确定',
            callback: action => {
                router.replace({
                    name: 'login',
                    query: {redirect: router.currentRoute.fullPath} //登录后再跳回此页面时要做的配置
                })
            }
        });
    }else if(response.data.errno== 201001){
        ElNotification.error(response.data.errmsg)
    }
    return response;
}, error => {
    console.log(error.response)
    if (error.response.status === 200) {
        ElNotification.error(error.response.statusText)
    }
    if (error.response.status === 500) {
        ElNotification.error(error.response.statusText)
        // toLogin()
    }
    return Promise.resolve(error.response);
})

// 时间
function getTimeStr(){
    let date = new Date();
    let year = date.getFullYear(); //获取当前年份
    let mon = date.getMonth() + 1; //获取当前月份
    let day = date.getDate();//获取当前日
    let h = date.getHours(); //获取小时
    let m = date.getMinutes(); //获取分钟
    let t3 = year + '' + p(mon) + '' + p(day) + '' + p(h) + '' + p(m);
    return t3
}
// 格式化小于10的时候 +0
function p(s) {
    return s < 10 ? '0' + s : s;
}
export default axios;
